/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * SelectFiles.java
 *
 * Created on 31/08/2011, 13:49:11
 */

package ufpb.compiladores.lexico.run.GUI;

import java.io.File;
import java.io.IOException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.filechooser.FileFilter;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import ufpb.compiladores.lexico.Automaton;
import ufpb.compiladores.lexico.AutomatonFactory;
import ufpb.compiladores.lexico.Enviroment;
import ufpb.compiladores.lexico.LexicalTable;
import ufpb.compiladores.lexico.Reader;
import ufpb.compiladores.lexico.XMLLoader;
import ufpb.compiladores.lexico.impl.AutomatonImpl;

/**
 *
 * @author Sarah
 */
public class SelectFiles extends javax.swing.JFrame {


    Vector caminhoAux = new Vector();
    Vector caminho = new Vector();
    Vector v = new Vector();
    //StringBuilder caminho;
    //StringBuilder caminhoAux;
    String caminhoXML;
    int i=-1, j=-1;

    /** Creates new form SelectFiles */
    public SelectFiles() {  
        
        initComponents();
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public SelectFiles(Document[] doc, File[] file) throws IOException{

        CallTables t = new CallTables(doc, file);
        t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        t.setVisible(true);
        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel1.setText("Arquivo de configuração");

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel2.setText("Arquivos para análise");

        jButton1.setFont(new java.awt.Font("Tahoma", 0, 14));
        jButton1.setText("Processar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setFont(new java.awt.Font("Tahoma", 0, 14));
        jButton2.setText("Browser");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jTextField1.setFont(new java.awt.Font("Tahoma", 0, 14));

        jTextField2.setFont(new java.awt.Font("Tahoma", 0, 14));

        jList1.setFont(new java.awt.Font("Tahoma", 0, 14));
        jScrollPane1.setViewportView(jList1);

        jButton3.setFont(new java.awt.Font("Tahoma", 0, 14));
        jButton3.setText("Browser");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setFont(new java.awt.Font("Tahoma", 0, 14));
        jButton4.setText("Adicionar");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 18));
        jLabel3.setText("Selecionar Arquivos");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 620, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 425, Short.MAX_VALUE)
                            .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 425, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButton3)
                                .addGap(9, 9, 9)
                                .addComponent(jButton4))
                            .addComponent(jButton2)))
                    .addComponent(jLabel1)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(273, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(276, 276, 276))
            .addGroup(layout.createSequentialGroup()
                .addGap(214, 214, 214)
                .addComponent(jLabel3)
                .addContainerGap(248, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(38, 38, 38)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 49, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton4)
                    .addComponent(jButton3)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addGap(46, 46, 46))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        JFileChooser fc = new JFileChooser();
        MyFileFilter filter = new MyFileFilter();
        fc.setFileFilter(filter);

       // fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int returnVal = fc.showOpenDialog(null);

            if(returnVal == JFileChooser.APPROVE_OPTION) {
            File arquivo = fc.getSelectedFile();
            jTextField1.setText("" + arquivo.getAbsolutePath());
            caminhoXML = arquivo.getAbsolutePath();
            }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        i+=1;
        JFileChooser fc = new JFileChooser();
        int returnVal = fc.showOpenDialog(null);
 
            if(returnVal == JFileChooser.APPROVE_OPTION) {
                File arquivo = fc.getSelectedFile();
                jTextField2.setText("" + arquivo.getAbsolutePath());
                caminhoAux.add(arquivo.getAbsolutePath());
            }
            //JOptionPane.showMessageDialog(this, "Erro.");
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        
         if(!jTextField2.getText().equals("")){

            j+=1;
            v.add(jTextField2.getText());
            jTextField2.setText("");
            jList1.setListData(v);
            caminho=caminhoAux;
        }
        else {
           JOptionPane.showMessageDialog(this, "Localize pelo menos um arquivo para adicionar.");
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        //Se a lista tiver vazia
        if(0 == jList1.getModel().getSize())
        {
            JOptionPane.showMessageDialog(this, "Adicione pelo menos um arquivo à lista.");
            return;
        }

        if(null == caminhoXML)
        {
            JOptionPane.showMessageDialog(this, "Adicione um arquivo de configuração.");
            return;
        }

        Document[] docs = new Document[jList1.getModel().getSize()];
        File[] files = new File[docs.length];
        XMLLoader loader = new XMLLoader(caminhoXML);
        Enviroment env = null;
        try {
            env = loader.createEnviroment();
        } catch (Exception ex) {
            Logger.getLogger(SelectFiles.class.getName()).log(Level.SEVERE, null, ex);
        }

        Document doc = null;
        LexicalTable[] lt = new LexicalTable[docs.length];
        
        for (int k=0; k<docs.length; k++){
            
           //files[1] = new File((String)jList1.getModel().getElementAt(1));
           files[k] = new File((String)caminho.get(k));
           Reader r = null;
            try {
                r = new Reader(files[k].toString());
            } catch (IOException ex) {
                Logger.getLogger(SelectFiles.class.getName()).log(Level.SEVERE, null, ex);
            }
           Automaton auto = AutomatonFactory.getAutomaton(env, r);
           
           docs[k].createElement("Raiz");
           lt[k] = auto.generateTable(docs[k], docs[k].getDocumentElement());
 
        }

        this.dispose();
        try {
            SelectFiles sf = new SelectFiles(docs, files);
        } catch (IOException ex) {
            Logger.getLogger(SelectFiles.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//GEN-LAST:event_jButton1ActionPerformed

    private class MyFileFilter extends FileFilter{

        @Override
        public boolean accept(File pathname) {

            if((pathname.getName().endsWith("xml"))|| pathname.isDirectory()){
                return true;
            }
            else {
                return false;
            }
        }


        @Override
        public String getDescription() {
            return ("Arquivo de configuração xml");
        }
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new SelectFiles().setVisible(true);

            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JList jList1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration//GEN-END:variables

}
